package com.ruoyi.personal.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file/upload")
public class FileUploadController {

    private static final String TARGET_FOLDER = "/uploads/";

    @GetMapping("test")
    public String test() {
        System.out.println("test");
        return "test success";
    }

    @PostMapping("/image")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Please select a file to upload.");
        }

        try {
            // 获取文件保存的路径
            String fileName = new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1");
            Path targetLocation = Paths.get(TARGET_FOLDER + fileName).toAbsolutePath().normalize();

            // 保存文件到磁盘
            Files.copy(file.getInputStream(), targetLocation);

            return ResponseEntity.ok("File uploaded successfully: " + fileName);

        } catch (IOException ex) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not upload the file: " + ex.getMessage());
        }
    }
}
